package com.gxa.learning.pc.controller;

import com.gxa.learning.core.common.ExceptionCode;
import com.gxa.learning.core.common.JsonResult;
import com.gxa.learning.core.exception.BusinessException;
import com.gxa.learning.core.pojo.RoleMenuVO;
import com.gxa.learning.core.util.ReturnJsonResultUtil;
import com.gxa.learning.pc.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lijianmin
 * @date 2021/12/07  16:02:56
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色的接口")
public class RoleController {
    /**
     * 定义一个数据常量
     */
    public static final Integer ZERO = 0;

    @Autowired
    private RoleService roleService;

    /**
     * 根据条件搜索的接口
     *
     * @param roleName   角色名称
     * @param company    公司名称
     * @param department 部门名称
     * @param state      角色状态
     * @param page       页码
     * @param size       每页数据量
     * @return 返回查询到的数据以及分页信息
     */
    @GetMapping("/select")
    @ApiOperation("根据条件搜索(如果条件为空 则为全查询)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleName", value = "角色名称", paramType = "query"),
            @ApiImplicitParam(name = "company", value = "公司名称", paramType = "query"),
            @ApiImplicitParam(name = "department", value = "部门名称", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "角色状态", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query")
    })
    public Map<String, Object> selectByLike(
            @RequestParam(name = "roleName", required = false) String roleName, @RequestParam(name = "company", required = false) String company
            , @RequestParam(name = "department", required = false) String department, @RequestParam(name = "state", required = false) Boolean state
            , @RequestParam(name = "page", required = false) Integer page, @RequestParam(name = "size", required = false) Integer size) throws BusinessException {
        List<RoleMenuVO> roleMenuVOS = roleService.selectByLike(roleName, company, department, state);
        // 获取总的记录数
        int size1 = roleMenuVOS.size();
        // 应该给前端返回的分页后的数据
        List<RoleMenuVO> roleMenuVOSByPage = new ArrayList<>(size1);
        // 如果分页条件不正常 则给前端抛异常
        if (page < 1 || size < 1) {
            throw new BusinessException(ExceptionCode.PAGE_SIZE_ERROR);
        }
        JsonResult jsonResult = new JsonResult();

        // 根绝page和size进行分页（物理，手动分页）,然后返回对应数据给前端
        if (page != null && !ZERO.equals(page)) {
            if (size != null && !ZERO.equals(size)) {
                // page和size都不为null或者0时
                if (size1 == 0) {
                    jsonResult.setData(roleMenuVOS);
                } else {
                    // 页数
                    int pageNum = size1 / size;
                    // 如果不能整除页数+1
                    if (size1 % size != 0) {
                        pageNum = size1 / size + 1;
                    }
                    // 遍历总的结果集，把分页的部分数据传入分页后的集合
                    for (int i = 0; i < size; i++) {
                        if ((page - 1) * size + i >= size1) {
                            break;
                        }
                        // 从(page - 1) * size开始的size或者小于size条数据装入新的集合中
                        roleMenuVOSByPage.add(roleMenuVOS.get((page - 1) * size + i));
                    }
                    // 传给前端
                    jsonResult.setData(roleMenuVOSByPage);
                }
            }
        } else {
            jsonResult.setData(roleMenuVOS);
        }
        jsonResult.put("count", size1);
        jsonResult.setCode("1");
        jsonResult.setMsg("查询成功");
        return jsonResult.getDataMap();
    }

    /**
     * 根据id删除角色的接口
     *
     * @param map 删除的角色ID (前端需要使用body接收 所以更改为map)
     * @return 返回消息
     * @throws BusinessException 操作中产生的异常
     */
    @PostMapping("/del")
    @ApiOperation("根据ID删除角色的接口")
    @ApiImplicitParam(name = "map", value = "删除的角色ID", paramType = "body")
    public Map<String, Object> del(@RequestBody Map<String, Object> map) throws BusinessException {
        if (map.get("id") == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        }
        roleService.deleteByRoleId(Long.parseLong(map.get("id").toString()));
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("删除成功");
        jsonResult.setCode("1");
        return jsonResult.getDataMap();
    }

    /**
     * 修改角色的接口
     *
     * @param map 修改的键值对
     * @return 返回是否成功的消息
     * @throws BusinessException 操作产生的异常
     */
    @PostMapping("/update")
    @ApiOperation("修改角色的接口")
    @ApiImplicitParam(name = "map", value = "修改的键值对", paramType = "body")
    public Map<String, Object> update(@RequestBody Map<String, Object> map) throws BusinessException {
        //判断必传项
        if (map.get("id") == null || map.get("mark") == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_ERROR);
        }
        //先删除此id相关的所有记录
        roleService.deleteByRoleId(Long.parseLong(map.get("id").toString()));

        //然后再进行添加
        Boolean add = roleService.add(map);

        //返回消息
        return ReturnJsonResultUtil.ReturnJsonResultUtil(add, "修改");
    }

    /**
     * 根据id修改角色状态的接口
     *
     * @param map 角色id (前端需要使用body接收 所以更改为map)
     * @return 返回是否成功
     * @throws BusinessException 操作中产生的异常
     */
    @PostMapping("/updateState")
    @ApiOperation("修改角色状态的接口")
    @ApiImplicitParam(name = "map", value = "map", paramType = "body")
    public Map<String, Object> updateState(@RequestBody Map<String, Object> map) throws BusinessException {

        System.out.println("-----------------------" + map);
        //判断必传项
        if (map.get("id") == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        }
        Boolean aBoolean = roleService.updateState(Long.valueOf(map.get("id").toString()));
        //返回消息
        return ReturnJsonResultUtil.ReturnJsonResultUtil(aBoolean, "修改状态");
    }

    /**
     * 添加角色的接口
     *
     * @param map 添加的字段
     * @return 返回消息
     * @throws BusinessException 操作中产生的异常
     */
    @PostMapping("/add")
    @ApiOperation("添加角色的方法")
    @ApiImplicitParam(name = "map", value = "添加需要的JSON的键值对", paramType = "body")
    public Map<String, Object> add(@RequestBody Map<String, Object> map) throws BusinessException {
        Boolean add = roleService.add(map);
        return ReturnJsonResultUtil.ReturnJsonResultUtil(add, "添加");
    }

}
